<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import barEchart from '@/components/Echart/barEchart.vue'
import lineYearlyChart from '@/components/Echart/lineYearlyChart.vue'
import { TScore, TScoreTotal } from '@/Types/score.d'
import { getSubjectBySpecificService } from '@/api/education/subject'
import { useRoute } from 'vue-router'
import { getScoreListBySpecificService } from '@/api/education/score'
import { getScoreTotalService } from '@/api/education/scoreTotal'
import router from '@/router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'

/**
 * 初始化
 */
const userStore = useUserStore()
const allScores = ref<TScore[]>([]) // 存储所有成绩数据
const scoreTotals = ref<TScoreTotal[]>([]) // 存储总分统计数据
const loading = ref(false)
const currentYear = ref('') // 当前选择的学年

/**
 * 数据获取
 */
// 获取路径中的userId
const userId = ref<number>(0)
const route = useRoute()
userId.value = Number(route.params.studentId)

// 获取科目名
const getSubjectName = async (subjectId: number) => {
	try {
		const res = await getSubjectBySpecificService([subjectId])
		if (res.data.code === 1) {
			return res.data.data[0].subject
		} else {
			ElMessage.error(res.data.msg || '获取科目名失败')
			return `科目${subjectId}`
		}
	} catch (error) {
		ElMessage.error('获取科目名失败')
		return `科目${subjectId}`
	}
}

// 获取所有成绩数据
const getAllScores = async () => {
	loading.value = true
	try {
		const res = await getScoreListBySpecificService({ studentId: userId.value })
		console.log(res.data.data)
		// console.log(userId.value)
		if (res.data.code === 1) {
			// 更新成绩数据，获取科目名
			const scoresWithSubjectNames = await Promise.all(
				res.data.data.map(async (score: TScore) => {
					const subjectName = await getSubjectName(score.subjectId)
					// console.log(subjectName)

					return { ...score, subjectName }
				})
			)
			allScores.value = scoresWithSubjectNames

			// 设置默认显示最新学年
			if (academicYears.value.length > 0) {
				currentYear.value = academicYears.value[0].value
			}
		} else {
			ElMessage.error(res.data.msg || '获取成绩失败')
		}
	} catch (error) {
		ElMessage.error('获取成绩失败')
	} finally {
		loading.value = false
	}
}

// 获取总分统计数据
const getScoreTotals = async () => {
	try {
		const res = await getScoreTotalService({ userId: userId.value })
		if (res.data.code === 1) {
			scoreTotals.value = res.data.data
		} else {
			ElMessage.error(res.data.msg || '获取成绩总分数据失败')
		}
	} catch (error) {
		ElMessage.error('获取成绩总分数据失败')
	}
}

// 获取考试情况标签
const getStatusLabel = (status: string) => {
	const map = {
		normal: '正常',
		absent: '缺考',
		violation: '作弊'
	}
	return map[status as keyof typeof map] || status
}

/**
 * 数据处理
 */
// 学年选项（从所有成绩中提取）
const academicYears = computed(() => {
	const years = [...new Set(allScores.value.map((score) => score.academicYear))]
	return years
		.map((year) => ({ value: year, label: year }))
		.sort((a, b) => b.value.localeCompare(a.value))
})

// 根据当前学年筛选的成绩数据
const filteredScores = computed(() => {
	if (!currentYear.value) return []
	return allScores.value.filter((score) => score.academicYear === currentYear.value)
})

// 当前年度的总分数据
const currentYearTotal = computed(() => {
	if (!currentYear.value) return null
	// TScoreTotal中使用的是academyYear
	return scoreTotals.value.find((total) => total.academyYear === currentYear.value)
})

// 修改图表数据的计算属性
const chartData = computed(() => {
	return {
		text: currentYear.value, // 标题显示当前学年
		subject: filteredScores.value.map((score) => score.subjectName), // X轴科目名称
		LLscore: filteredScores.value.map((score) => score.theoryTotal), // 理论成绩
		SJscore: filteredScores.value.map((score) => score.practiceTotal) // 实践成绩
	}
})

/**
 * 学年成绩走势图数据
 */
const yearlyChartData = computed(() => {
	// 确保有数据才处理
	if (!scoreTotals.value || scoreTotals.value.length === 0) {
		console.log('scoreTotals为空，返回空数据')
		return {
			text: '学年成绩趋势',
			years: [],
			theoryTotals: [],
			practiceTotals: []
		}
	}

	try {
		// 按年份排序，从早到晚
		const sortedTotals = [...scoreTotals.value].sort((a, b) =>
			(a.academyYear || '').localeCompare(b.academyYear || '')
		)

		const result = {
			text: '学年成绩趋势',
			years: sortedTotals.map((total) => total.academyYear || '未知学年'),
			theoryTotals: sortedTotals.map((total) => total.theoryTotal || 0),
			practiceTotals: sortedTotals.map((total) => total.practiceTotal || 0)
		}
		return result
	} catch (error) {
		return {
			text: '学年成绩趋势',
			years: [],
			theoryTotals: [],
			practiceTotals: []
		}
	}
})

/**
 * 操作逻辑
 */
// 显示返回按钮
const showBackButton = computed(() => {
	// console.log(userStore.loginInfo.userId, userId.value)
	return userStore.userInfo.userInfo.userId != userId.value
})
// 返回上一级
const goBack = () => {
	router.back()
}

/**
 * 生命周期
 */
onMounted(async () => {
	await Promise.all([getAllScores(), getScoreTotals()])
})
</script>

<template>
	<div class="user-score">
		<!-- 筛选区域 -->
		<el-card class="filter-card">
			<div class="filter-form">
				<el-button type="primary" :icon="ArrowLeft" @click="goBack" v-if="showBackButton"
					>返回</el-button
				>
				<el-select v-model="currentYear" placeholder="选择学年">
					<el-option
						v-for="item in academicYears"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					/>
				</el-select>
			</div>
		</el-card>

		<!-- 成绩展示区域 -->
		<el-card class="score-card" v-loading="loading">
			<!-- 图表展示 -->
			<div class="chart-container" style="width: 100%" v-if="filteredScores.length">
				<barEchart :chartData="chartData" />
			</div>

			<div class="score-content">
				<!-- 表格展示 -->
				<div class="table-wrapper">
					<el-table :data="filteredScores" border stripe style="width: fit-content">
						<el-table-column prop="subjectName" label="科目" width="120" align="center" />

						<!-- 理论成绩 -->
						<el-table-column label="理论成绩" align="center">
							<el-table-column label="期中" width="70" align="center">
								<template #default="{ row }">
									<span class="score-cell">{{ row.midTermTheory || '-' }}</span>
								</template>
							</el-table-column>
							<el-table-column label="期末" width="70" align="center">
								<template #default="{ row }">
									<span class="score-cell">{{ row.finalTheory || '-' }}</span>
								</template>
							</el-table-column>
							<el-table-column label="总分" width="120" align="center">
								<template #default="{ row }">
									<div class="score-cell">
										<span class="total">{{ row.theoryTotal || '-' }}</span>
										<el-tag
											size="small"
											:type="row.aboutTheory === 'normal' ? 'success' : 'danger'"
										>
											{{ getStatusLabel(row.aboutTheory) }}
										</el-tag>
									</div>
								</template>
							</el-table-column>
						</el-table-column>

						<!-- 实践成绩 -->
						<el-table-column label="实践成绩" align="center">
							<el-table-column label="期中" width="70" align="center">
								<template #default="{ row }">
									<span class="score-cell">{{ row.midTermPractice || '-' }}</span>
								</template>
							</el-table-column>
							<el-table-column label="期末" width="70" align="center">
								<template #default="{ row }">
									<span class="score-cell">{{ row.finalPractice || '-' }}</span>
								</template>
							</el-table-column>
							<el-table-column label="总分" width="120" align="center">
								<template #default="{ row }">
									<div class="score-cell">
										<span class="total">{{ row.practiceTotal || '-' }}</span>
										<el-tag
											size="small"
											:type="row.aboutPractice === 'normal' ? 'success' : 'danger'"
										>
											{{ getStatusLabel(row.aboutPractice) }}
										</el-tag>
									</div>
								</template>
							</el-table-column>
						</el-table-column>
					</el-table>

					<!-- 空数据展示 -->
					<el-empty v-if="!filteredScores.length" description="暂无成绩数据" />

					<!-- 总分统计展示 -->
					<div class="total-overview" v-if="currentYearTotal">
						<div class="overview-content">
							<div class="overview-row">
								<div class="overview-item">
									<span class="label">理论总分</span>
									<span class="value theory-value">{{ currentYearTotal.theoryTotal }}</span>
								</div>
								<div class="overview-item">
									<span class="label">理论排名</span>
									<span class="value rank-value">{{ currentYearTotal.rankTheoryTotal }}</span>
								</div>
								<el-divider direction="vertical" />
								<div class="overview-item">
									<span class="label">实践总分</span>
									<span class="value practice-value">{{ currentYearTotal.practiceTotal }}</span>
								</div>
								<div class="overview-item">
									<span class="label">实践排名</span>
									<span class="value rank-value">{{ currentYearTotal.rankPracticeTotal }}</span>
								</div>
							</div>

							<el-divider style="margin: 5px;" />

							<!-- 学年成绩走势图 -->
							<div style="height: 100%;">
								<lineYearlyChart :data="yearlyChartData" />
							</div>
						</div>
					</div>
				</div>
			</div>
		</el-card>
	</div>
</template>

<style lang="scss" scoped>
.user-score {
	height: 100%;
	.filter-card {
		margin-bottom: 20px;

		.filter-form {
			display: flex;
			justify-content: space-between;
			align-items: center;
			gap: 20px;

			.el-select {
				width: 200px;
			}
		}
	}

	.score-card {
		.chart-container {
			margin-bottom: 20px;
			height: 300px;
			width: 50%;
		}

		.score-content {
			display: flex;
			gap: 10px;
			flex-direction: column;

			.table-wrapper {
				display: flex;
				// flex-direction: column;
				width: 100%;
			}

			.total-overview {
				width: 90vh;
				height: fit-content;
				background-color: #f8f9fa;
				border-radius: 8px;
				padding: 12px 0;
				margin-top: 20px;
				margin-left: 10px;
				box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
				border: 1px solid #ebeef5;

				.overview-header {
					font-size: 16px;
					font-weight: bold;
					color: #333;
					margin-bottom: 15px;
					text-align: center;
					border-bottom: 1px solid #eaeaea;
					padding-bottom: 10px;
				}

				.overview-content {
					display: flex;
					flex-direction: column;
					height: 32vh;

					.overview-row {
						display: flex;
						flex-direction: row;
						justify-content: space-between;
						width: 100%;
						margin: 0;
					}

					.overview-item {
						display: flex;
						flex-direction: column;
						align-items: center;
						gap: 8px;
						padding: 0 10px;
						flex: 1;
						position: relative;

						// &:not(:last-child):after {
						// 	content: '';
						// 	position: absolute;
						// 	right: 0;
						// 	top: 10%;
						// 	height: 80%;
						// 	width: 1px;
						// 	background-color: #eaeaea;
						// }

						.label {
							font-size: 14px;
							color: #909399;
							font-weight: 500;
						}

						.value {
							font-size: 18px;
							font-weight: bold;

							&.theory-value {
								color: #409eff;
							}

							&.practice-value {
								color: #67c23a;
							}

							&.rank-value {
								color: #e31ce7;
							}
						}
					}
				}
			}

			.yearly-chart-card {
				margin-top: 20px;

				.chart-title {
					text-align: center;
					font-weight: bold;
					color: #409eff;
				}
			}
		}

		.score-cell {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 5px;
			.total {
				font-size: 16px;
				font-weight: bold;
				color: #2676ee;
				margin-right: 25px;
			}

			.el-tag {
				position: absolute;
				right: 5px;
			}
		}

		.rank {
			font-weight: bold;
			color: #f56c6c;
		}

		:deep(.el-table) {
			margin-top: 20px;

			th {
				background-color: #f5f7fa;
			}

			.el-table__header .el-table__cell {
				background-color: #ebeef5;
			}
		}
	}
}

.el-divider--vertical {
	height: 3em;
}
</style>
